package com.itheima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.admin.mapper.AdUserMapper;
import com.itheima.admin.pojo.AdUser;
import com.itheima.admin.service.AdUserService;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    /**
     * 登录校验
     *
     * @param paramMap
     */
    @Override
    public Map<String, Object> loginCheck(Map<String, String> paramMap) {
        //1. 获取参数
        String name = paramMap.get("name");
        String password = paramMap.get("password");
        //2. 参数非空校验
        if(StringUtils.isEmpty(name) || StringUtils.isEmpty(password)){
            throw new LeadNewsException("用户名或密码错误！");
        }
        //3. 通过登录名查询用户信息
        AdUser adUser = query().eq("name", name).one();
        if(null == adUser) {
            //3.1查不到数据则报错
            throw new LeadNewsException("用户名或密码错误！");
        }
        //4. 校验密码是否相同
        //mdt(前端的密码+盐) eqauls(数据库的密码)
        password += adUser.getSalt();
        String digestAsHex = DigestUtils.md5DigestAsHex(password.getBytes());
        System.out.println("digestAsHex = " + digestAsHex);
        System.out.println(adUser.getPassword());
        //不相同：报错
        if(!adUser.getPassword().equals(digestAsHex)){
            throw new LeadNewsException("用户名或密码错误!");
        }
        //5. 相同则生成token
        String token = AppJwtUtil.createToken(adUser.getId().longValue());

        //6. 构建返回的数据
        Map<String, Object> result = new HashMap<>();
        adUser.setPassword(null);
        adUser.setSalt(null);
        result.put("token",token);
        result.put("user",adUser);
        return result;
    }
}
